import frappe
from frappe import _
from frappe.utils import now_datetime
from link_history.utils.link_history import update_link_history, clear_link_history, is_link_history_disabled,CACHE_PREFIX

@frappe.whitelist()
def update_history(link_doctype, link_name, reference_doctype=None):
    """更新链接字段的历史记录"""
    # 检查是否禁用
    if is_link_history_disabled():
        return {"status": "disabled", "message": "Link History 功能已禁用"}
    try:
        # 尝试更新历史记录
        update_link_history(link_doctype, link_name, reference_doctype)
        return {"status": "success"}
    except frappe.exceptions.TimestampMismatchError:
        # 如果发生时间戳不匹配错误，等待一段时间后重试
        frappe.db.rollback()
        frappe.local.message_log = []
        
        # 直接清除缓存
        cache_key = f"{link_doctype}:{reference_doctype or 'all'}:{frappe.session.user}"
        frappe.cache.hdel(CACHE_PREFIX, cache_key)
        
        # 返回成功，不再重试
        return {"status": "success", "message": "Cache cleared"}
    except Exception as e:
        # 记录其他错误但不中断流程
        frappe.log_error(f"更新历史记录时出错: {e}", "Link History")
        return {"status": "error", "message": str(e)}

@frappe.whitelist()
def clean_history():
    """清理历史记录中的无效数据"""
    # 删除没有 link_name 或 link_title 的记录
    frappe.db.sql("""
        DELETE FROM `tabLink History Record` 
        WHERE link_name IS NULL OR link_name = '' OR link_name = 'undefined'
        OR link_title IS NULL OR link_title = '' OR link_title = 'undefined'
    """)
    
    # 更新缓存
    frappe.cache.delete_key(CACHE_PREFIX)
    
    frappe.db.commit()
    return {"status": "success"}

@frappe.whitelist()
def clear_history(link_doctype=None, reference_doctype=None):
    """清除用户的链接历史记录"""
    try:
        clear_link_history(link_doctype, reference_doctype)
        return {"status": "success"}
    except Exception as e:
        frappe.log_error(f"清除历史记录时出错: {e}", "Link History")
        return {"status": "error", "message": str(e)} 